package study.springcloud.gateway.support.utils;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.Map;

/**
 * 响应写入
 */
public final class WriteUtils {

    private static final String DEFAULT_CONTENT_TYPE = "application/json;charset=UTF-8";

    private WriteUtils() {
    }

    public static Mono<Void> write(ServerWebExchange exchange, String body) {
        return write(exchange, body, Collections.EMPTY_MAP);
    }

    public static Mono<Void> write(ServerWebExchange exchange, String body, Map<String, String> headers) {
        return write(exchange, body, headers, DEFAULT_CONTENT_TYPE);
    }

    /**
     * 写入
     */
    static Mono<Void> write(ServerWebExchange exchange,
                            String body,
                            Map<String, String> headers,
                            String contentType) {
        //
        ServerHttpResponse response = WebUtils.getServerHttpResponse(exchange);
        // 响应码
        response.setStatusCode(HttpStatus.OK);
        // 响应头
        WebUtils.addResponseHeader(exchange, "Content-Type", contentType);
        if (CollectionUtil.isNotEmpty(headers)) {
            headers.entrySet()
                    .forEach(e -> WebUtils.addResponseHeader(exchange, e.getKey(), e.getValue()));
        }
        // 响应体
        byte[] bodyByte = body.getBytes();
        DataBuffer buffer = response.bufferFactory()
                .wrap(bodyByte);
        // 写入
        return response.writeWith(Mono.just(buffer));
    }
}
